package com.example.administrator.exkotlin.jetpack.room

import android.os.Bundle
import android.util.Log
import android.view.View
import com.example.administrator.exkotlin.R
import com.example.administrator.exkotlin.activity.BaseActivity
import com.example.administrator.exkotlin.jetpack.room.dao.BookDao
import com.example.administrator.exkotlin.jetpack.room.dao.UserDao
import com.example.administrator.exkotlin.jetpack.room.entity.Book
import com.example.administrator.exkotlin.jetpack.room.entity.User
import kotlinx.android.synthetic.main.activity_room.*
import kotlin.concurrent.thread

class RoomActivity : BaseActivity(), View.OnClickListener {

    private val TAG="RoomActivity"
    private lateinit var userDao :UserDao
    private lateinit var bookDao: BookDao
    val firstName = "tom"
    val lastName = "ford"
    var age = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_room)

        initData()
    }

    private fun initData() {
        userDao=MyDatabase.getDatabase(this).userDao()
        bookDao=MyDatabase.getDatabase(this).bookDao()
        btn_add_room.setOnClickListener(this)
        btn_remove_room.setOnClickListener(this)
        btn_update_room.setOnClickListener(this)
        showData()
    }

    override fun onClick(v: View?) {
        when (v) {
            btn_add_room -> {
                val num = age++
                val newUsber = User("$firstName $num", "$lastName $num", num)
                Log.i(TAG, newUsber.id.toString())

                userDao.inserUser(newUsber)

                val newBook=Book("$firstName $num", num,"$lastName $num")
                bookDao.insertBook(newBook)

            }
            btn_remove_room -> {
                val findLastUser = userDao.findFirstUser()
                userDao.deleteUser(findLastUser)
            }
            btn_update_room->{
                val newuser = userDao.loadAllUSers()[0]
                newuser.firstName=newuser.firstName+"__new"
                newuser.lastName=newuser.lastName+"__new"
                userDao.updateUser(newuser)
            }
        }
        showData()
    }

    private fun showData() {
        val loadAllUSers =userDao.loadAllUSers()
        tv_detalis.text = loadAllUSers.toString()
        tv_detalis_book.text = bookDao.loadAllUBooks().toString()

    }

}
